package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        try {
            //1.创建bucket
            makeBucket();
            //2.获取文件上传名称
            String fileName = getFileName(file);
            //3.上传文件
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .contentType(file.getContentType())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            //4.返回文件访问地址
            String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + fileName;
            System.out.println("文件地址: " + url);
            return url;
        } catch (Exception e) {
            //5.异常处理
            System.out.println("文件上传失败");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //获取文件名称
    private String getFileName(MultipartFile file) {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String subType = originalFilename.substring(lastIndexOf);

        String date = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        //生成uuid
        String uuid = UUID.randomUUID().toString().replace("-","");
        //组成文件名称
        String fileName = date + uuid + subType;
        return fileName;
    }

    //校验bucket是否存在
    private void makeBucket() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build();
        boolean bucketFlag = minioClient.bucketExists(bucketExistsArgs);

        //如果不存在则创建
        if (!bucketFlag) {
            //创建bucket
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build();
            minioClient.makeBucket(makeBucketArgs);

            //设置bucket权限
            SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(getConfig()).build();
            minioClient.setBucketPolicy(setBucketPolicyArgs);
        }
    }

    private String getConfig() {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(minioProperties.getBucketName());
    }
}

